package cn.tedu.csmall.order.webapi.controller;

import cn.tedu.csmall.commons.pojo.order.dto.OrderAddDTO;
import cn.tedu.csmall.commons.pojo.order.entity.Order;
import cn.tedu.csmall.commons.pojo.stock.dto.StockReduceCountDTO;
import cn.tedu.csmall.commons.restful.JsonPage;
import cn.tedu.csmall.commons.restful.JsonResult;
import cn.tedu.csmall.commons.restful.ResponseCode;
import cn.tedu.csmall.order.service.IOrderService;
import cn.tedu.csmall.order.webapi.service.impl.OrderServiceImpl;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/base/order")
@Api(tags = "订单管理模块")
public class OrderController {

    @Autowired
    private IOrderService orderService;

    @PostMapping("/add")
    @ApiOperation("新增订单")
    @SentinelResource(value = "新增订单",
            blockHandler = "blockError",
            fallback = "fallbackError"
    )
    public JsonResult orderAdd(OrderAddDTO orderAddDTO) {
        orderService.orderAdd(orderAddDTO);
        return JsonResult.ok("新增订单完成!");
    }

    // Sentinel自定义限流方法规则
    // 1.访问修饰符必须是public
    // 2.返回值类型必须和被限流的控制方法一致
    // 3.方法名称必须和@SentinelResource注解中blockHandler设置的名称一致
    // 4.参数列表也是和控制器方法一致,在末尾额外添加一个BlockException类似的参数
    public JsonResult blockError(OrderAddDTO orderAddDTO,
                                 BlockException e) {
        // 这个方法会在请求被限流时执行,返回值应包含相应的提示信息
        return JsonResult.failed(
                ResponseCode.INTERNAL_SERVER_ERROR, "服务器忙,请稍后再试");
    }

    public JsonResult fallbackError(OrderAddDTO orderAddDTO,
                                    Throwable throwable) {
        throwable.printStackTrace();
        return JsonResult.failed(ResponseCode.INTERNAL_SERVER_ERROR, "方法运行发生异常，执行了降级方法");
    }

    @GetMapping("/page")
    @ApiOperation("分页查询所有订单")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "页码",name="page",example = "1"),
            @ApiImplicitParam(value = "每页条数",name="pageSize",example = "10")
    })
    public JsonResult<JsonPage<Order>> pageOrder(Integer page, Integer pageSize){
        JsonPage<Order> pageInfo = orderService.getAllOrdersByPage(page, pageSize);
        return JsonResult.ok("查询完成!",pageInfo);
    }
}
